package com.cxs.socketdemo02.slice;

import com.cxs.socketdemo02.ResourceTable;
import com.cxs.socketdemo02.util.ThreadPoolUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.wifi.IpInfo;
import ohos.wifi.WifiDevice;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

public class MainAbilitySlice extends AbilitySlice {

    private static final String TAG = MainAbilitySlice.class.getSimpleName();
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, TAG);
    private static final int PORT = 10006;
    private static final String CHARSET_NAME = "UTF-8";
    TextField tfInput;
    Text textInfo;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        // 本机IP
        textInfo = (Text) findComponentById(ResourceTable.Id_text_info);
        ((Text)findComponentById(ResourceTable.Id_text_ip)).setText(getLocalIpAddress());
        tfInput = (TextField)findComponentById(ResourceTable.Id_tf_input);
        // 服务器地址
        tfInput.setText("192.168.1.100");

        findComponentById(ResourceTable.Id_btn_start_server)
                .setClickedListener(this::startServer);
        findComponentById(ResourceTable.Id_btn_btn_send)
                .setClickedListener(this::sendMessage);
    }

    /**
     * 客户端向服务端发送消息
     * @param component
     */
    private void sendMessage(Component component) {
        new Thread(() -> {
            String ip = tfInput.getText();
            NetManager netManager = NetManager.getInstance(getContext());

            if (!netManager.hasDefaultNet()) {
                return;
            }
            NetHandle netHandle = netManager.getDefaultNet();

            // 通过Socket绑定来进行数据传输
            DatagramSocket socket = null;
            try {
                InetAddress address = netHandle.getByName(ip);

                socket = new DatagramSocket();
                netHandle.bindSocket(socket);

                byte[] buffer = "www.baidu.com".getBytes(CHARSET_NAME);
                DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, PORT);
                // 发送数据
                socket.send(request);
            } catch(IOException e) {
                HiLog.error(LABEL_LOG, "发送失败");
            }finally {
                if (socket != null) {
                    socket.close();
                    HiLog.error(LABEL_LOG, "发送失败");
                }
            }
        }).start();



    }

    /**
     * 开启服务端
     * @param component
     */
    private void startServer(Component component) {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(PORT)){
                DatagramPacket packet = new DatagramPacket(new byte[255], 255);
                while (true) {
                    socket.receive(packet);
                    String message = new String(packet.getData(), packet.getOffset(), packet.getLength(), CHARSET_NAME);
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
                HiLog.error(LABEL_LOG, "开启失败");
            }
        }).start();
    }

    /**
     * 获取本机Ip
     * @return
     */
    private String getLocalIpAddress() {
        WifiDevice wifiDevice = WifiDevice.getInstance(getContext());
        Optional<IpInfo> ipInfo = wifiDevice.getIpInfo();
        int ip = ipInfo.get().getIpAddress();
        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF);
    }

}